# -*- coding: utf-8 -*-
from scrapy import Request
from scrapy.exceptions import IgnoreRequest
from zc_core.client.mongo_client import Mongo
from zc_core.util.http_util import retry_request
from ctaxccgp.rules import *
from zc_core.spiders.base import BaseSpider


class SpuSpider(BaseSpider):
    name = 'spu'

    # 常用链接
    spu_url = 'https://www.zcygov.cn/api/micro/spu/findSpecificationList?timestamp=1654330470&categoryId={}&brandId={}'

    def __init__(self, batchNo=None, *args, **kwargs):
        super(SpuSpider, self).__init__(batchNo=batchNo, *args, **kwargs)
        self.cookie = {
            'districtCode': '001000',
            'districtName': '%E5%9B%BD%E5%AE%B6%E7%A8%8E%E5%8A%A1%E6%80%BB%E5%B1%80%E6%9C%AC%E7%BA%A7',
            'SESSION': 'NTNlMzRjODAtZWY0Ni00ZWMyLTg1ZTUtMzRhZDExNTFlODg0',
        }

    def start_requests(self):
        rows = list(Mongo().get_collection('brand_pool').find())
        self.logger.info('任务：%s' % (len(rows)))
        for row in rows:
            cat_id = row.get('catId')
            cat_name = row.get('catName')
            brand_id = row.get('code')
            brand_name = row.get('name')
            yield Request(
                url=self.spu_url.format(cat_id, brand_id),
                meta={
                    'reqType': 'spu',
                    'batchNo': self.batch_no,
                    'catalogId': cat_id,
                    'catalogName': cat_name,
                    'brandId': brand_id,
                    'brandName': brand_name,
                },
                headers={
                    'Host': 'www.zcygov.cn',
                    'Connection': 'keep-alive',
                    'Accept': '*/*',
                    'X-Requested-With': 'XMLHttpRequest',
                    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.25 Safari/537.36 Core/1.70.3741.400 QQBrowser/10.5.3863.400',
                    'Referer': 'https://www.zcygov.cn/item-center-front/publishgoods/selectCategory?current=0&categoryType=0',
                    'Accept-Encoding': 'gzip, deflate, br',
                    'Accept-Language': 'zh-CN,zh;q=0.9',
                },
                cookies=self.cookie,
                callback=self.parse_spu,
                errback=self.error_back,
                priority=100,
            )

    def parse_spu(self, response):
        meta = response.meta
        cat_id = meta.get('catalogId')
        br_id = meta.get('brandId')
        # 处理品类列表
        spu_list = parse_spu(response)
        if spu_list:
            self.logger.info('SPU: cat=%s, br=%s, cnt=%s' % (cat_id, br_id, len(spu_list)))
            yield Box('spu', self.batch_no, spu_list)
        else:
            self.logger.error('NO SPU: cat=%s, br=%s' % (cat_id, br_id))
